package zuel.innovation.disley.user.controller;

import cn.fabrice.common.constant.BaseConstants;
import cn.fabrice.common.pojo.BaseResult;
import cn.fabrice.common.pojo.DataResult;
import cn.fabrice.jfinal.annotation.Param;
import cn.fabrice.jfinal.annotation.ValidateParam;
import cn.fabrice.jfinal.constant.ValidateRuleConstants;
import cn.fabrice.jfinal.ext.cros.interceptor.CrossInterceptor;
import cn.fabrice.kit.Kits;
import com.alibaba.fastjson.JSONObject;
import com.jfinal.aop.Before;
import com.jfinal.aop.Clear;
import com.jfinal.aop.Inject;
import com.jfinal.core.Controller;
import com.jfinal.core.Path;
import com.jfinal.kit.HashKit;
import com.jfinal.kit.Kv;
import com.jfinal.kit.PathKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.upload.UploadFile;
import zuel.innovation.disley.common.module.Document;
import zuel.innovation.disley.common.module.Token;
import zuel.innovation.disley.common.module.User;
import zuel.innovation.disley.interceptor.AuthInterceptor;
import zuel.innovation.disley.user.service.UserService;
import zuel.innovation.disley.user.service.UserSessionService;

import java.io.File;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

@Before(CrossInterceptor.class)
@Path("/user")
@ValidateParam


public class UserController extends Controller {
    @Inject
    UserService service;
    @Inject
    UserSessionService sessionService;


    /**
     * 管理员分页获取所有用户
     *
     * @param page     页数
     * @param pageSize 每页的信息数目
     */
    @Param(name = "page", required = true)
    @Param(name = "pageSize", required = true)
    public void getAllUsersByPages(int page, int pageSize) {
        Page<Record> users = Db.paginate(page, pageSize, "select u_id,u_phone,u_name,u_sex,u_email,u_grade,u_ins,u_major,u_group,u_identity", "from user where u_deleted=0");
        renderJson(DataResult.data(users));
    }


    /**
     * 管理员删除团队成员（踢出成员）
     *
     * @param uId 用户Id
     */
    @Param(name = "uId", required = true)
    public void deleteUser(int uId) {
        Kv cond = Kv.by("uId", uId);
        User user = service.get(cond, "getUserById");
        user.setUDeleted(1);
        renderJson(user.update() ? BaseResult.ok() : BaseResult.fail());

    }


    /**
     * 获取团队人数
     */
    public void getNumber() {
        User num = service.get("getNumber");
        renderJson(DataResult.data(num));
    }


    /**
     * 按身份搜索用户，分页展示
     *
     * @param uIdentity 身份 0-团队成员，1-管理员，默认是0
     * @param page      页数
     * @param pageSize  每页信息条数
     */
    @Param(name = "page", required = true)
    @Param(name = "pageSize", required = true)
    @Param(name = "uIdentity", required = true)
    public void selectUserByIdentity(int uIdentity, int page, int pageSize) {
        Page<Record> users = Db.paginate(page, pageSize, "select u_id,u_phone,u_name,u_sex,u_email,u_grade,u_ins,u_major,u_group,u_identity", "from user where u_deleted=0 and u_identity=" + uIdentity);
        renderJson(DataResult.data(users));
    }


    /**
     * 按搜索内容模糊查找用户
     *
     * @param content 内容
     */
    @Param(name = "content", required = true)
    public void fuzzySearchUser(String content) {
        Kv cond = Kv.by("content", content);
        List<User> userList = service.list(cond, "fuzzySearchUser");
        renderJson(DataResult.data(userList));
    }


    /**
     * 登录
     *
     * @param uPhone 手机
     * @param uPwd   密码
     * @throws ParseException
     */
    @Clear(AuthInterceptor.class)
    @Param(name = "uPhone", required = true)
    @Param(name = "uPwd", required = true)
    public void login(String uPhone, String uPwd) throws ParseException {
        Kv cond = Kv.by("uPhone", uPhone);
        User user = service.get(cond, "getByUserPhone");
        if (user == null) {
            renderJson(BaseResult.fail("该用户不存在"));
            return;
        }
        String hashPwd = HashKit.sha256(user.getUSalt() + HashKit.md5(uPwd));
        if (!hashPwd.equals(user.getUPwd())) {
            renderJson(BaseResult.fail("密码错误"));
            return;
        }
        String token = Kits.getUuid();
        HashMap<String, Object> data = new HashMap<>();
        if (sessionService.add(user.getUId(), token)) {
            Token userToken = new Token();
            userToken.setTToken(token);
            userToken.setUId(user.getUId());
            data.put("uId", user.getUId());
            data.put("token", token);
            data.put("identity", user.getUIdentity());
            renderJson(DataResult.data(data));
            return;
        }
        renderJson(BaseResult.fail("插入token表失败"));
    }


    /**
     * 退出登录
     */
    public void leave() {
        int uId = getAttr(BaseConstants.ACCOUNT_ID);
        Kv cond = Kv.by("uId", uId);
        Token userToken = sessionService.get(cond, "get");
        if (userToken == null) {
            renderJson("无该条记录");
            return;
        } else {
            userToken.setTDeleted(1);
            renderJson(userToken.update() ? BaseResult.ok() : BaseResult.fail());
        }
    }


//    @Param(name="uPhone",required = true,rule = ValidateRuleConstants.Key.MOBILE)
//    @Param(name = "uPwd",required = true)
//    public void register(String uPhone,String uPwd){
//        Kv cond= Kv.by("uPhone",uPhone);
//        User user=service.get(cond,"getByUserPhone");
//        if(user!=null){
//            renderJson(BaseResult.fail("用户已存在"));
//            return;
//        }else {
//            String salt=HashKit.generateSaltForSha256();
//            User user1=new User();
//            user1.setUSalt(salt);
//            user1.setUPwd(HashKit.sha256(salt+HashKit.md5(uPwd)));
//            user1.setUPhone(uPhone);
//            renderJson(user1.save()?BaseResult.ok():BaseResult.fail());
//        }
//
//    }


    /**
     * 用户显示个人主页
     */
    public void selectUser() {
        int id = getAttr(BaseConstants.ACCOUNT_ID);
        Kv cond = Kv.by("uId", id);
        User user = service.get(cond, "getUserById");
        if (user == null) {
            renderJson(BaseResult.fail("token值错误"));
        } else {
            renderJson(DataResult.data(user));
        }
    }


    /**
     * 用户完善个人信息
     *
     * @param uSex   性别  0-女，1-男
     * @param uEmail 邮箱
     * @param uGroup 分组 0-未分组 1-前端 2-后端
     * @param uGrade 年级 1-大一，2-大二，3-大三，4-大四，5-研究生及以上
     * @param uName  姓名
     * @param uIns   学院
     * @throws ParseException
     */
    @Param(name = "uSex", required = true)
    @Param(name = "uEmail", required = true, rule = ValidateRuleConstants.Key.EMAIL)
    @Param(name = "uIdentity", required = true)
    @Param(name = "uGroup", required = true)
    @Param(name = "uGrade", required = true)
    @Param(name = "uName", required = true)
    @Param(name = "uIns", required = true)
    public void updateUser(int uSex, String uEmail, int uGroup, int uGrade, String uName, String uIns) throws ParseException {
        int id = getAttr(BaseConstants.ACCOUNT_ID);
        Kv cond = Kv.by("uId", id);
        User user = service.get(cond, "getUserById");
        if (user == null) {
            renderJson(BaseResult.fail("token值错误"));
        } else {
            user.setUSex(uSex);
            user.setUName(uName);
            user.setUEmail(uEmail);
            user.setUIns(uIns);
            user.setUGroup(uGroup);
            user.setUGrade(uGrade);

            renderJson(user.update() ? BaseResult.ok() : BaseResult.fail());
        }
        return;
    }


    /**
     * 用户修改密码
     *
     * @param uPwd 密码
     */
    @Param(name = "uPwd", required = true)
    public void updateUpwd(String uPwd) {
        int uId = getAttr(BaseConstants.ACCOUNT_ID);
        Kv cond = Kv.by("uId", uId);
        User user = service.get(cond, "updatePassword");
        if (user == null) {
            renderJson(BaseResult.fail("用户不存在"));
        } else {
            String salt = HashKit.generateSaltForSha256();
            user.setUSalt(salt);
            user.setUPwd(HashKit.sha256(salt + HashKit.md5(uPwd)));
            user.setUId(uId);
            renderJson(user.update() ? DataResult.data(user) : DataResult.fail("修改失败"));
        }
    }

    /**
     * 管理员新增用户
     *
     * @param uName  姓名
     * @param uPhone 电话
     * @throws ParseException
     */
    @Param(name = "uName", required = true)
    @Param(name = "uPhone", required = true, rule = ValidateRuleConstants.Key.MOBILE)
    public void addNewMember(String uName, String uPhone) throws ParseException {
        Kv cond= Kv.by("uPhone",uPhone);
        User user1=service.get(cond,"getByUserPhone");
        if(user1!=null){
            renderJson(BaseResult.fail("用户已存在"));
            return;
        }
        User user = new User();
        user.setUName(uName);
        user.setUPhone(uPhone);
        user.setUIdentity(0);
        String uPwd = "666666"; //默认密码
        String salt = HashKit.generateSaltForSha256();
        user.setUSalt(salt);
        user.setUPwd(HashKit.sha256(salt+HashKit.md5(HashKit.md5(uPwd))));
        SimpleDateFormat df = new SimpleDateFormat("yyyy/MM/dd hh:mm:ss");
        Date uCreate = df.parse(df.format(System.currentTimeMillis()));
        user.setUCreate(uCreate);
        renderJson(user.save() ? DataResult.data(user) : DataResult.fail("添加失败"));
    }

    /**
     * 管理员修改用户身份
     *
     * @param uIdentity 0-团队成员，1-管理员，默认是0
     * @param uId       用户Id
     */
    @Param(name = "uIdentity", required = true)
    @Param(name = "uId", required = true)
    public void updateIdentity(int uIdentity, int uId) {
        User user = service.get(uId);
        user.setUIdentity(uIdentity);
        renderJson(user.update() ? BaseResult.ok() : BaseResult.fail());
    }


    /**
     * 上传文件
     */
    // 设置在访问此方法时先被拦截器拦截处理
    @Clear(AuthInterceptor.class)
    public void upload() {
        UploadFile document =getFile("file");
        System.out.println("文件名："+document.getFileName());
//        renderJson(BaseResult.ok());

        // 获得上传文件的原始文件名
        String fileName = document.getFileName();
        System.out.println("文件名:"+fileName);
//        // 获得文件的后缀名
        String suffix = fileName.substring(fileName.lastIndexOf(".")+1);
        System.out.println("前缀名"+suffix);
//        // 重命名上传的文件
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddhhmmss");
        String lastThreeLetter = fileName.substring(fileName.lastIndexOf("."));
        String newName = sdf.format(new Date())+(int)(Math.random()*10000)+lastThreeLetter;
        System.out.println("新名名"+newName);
        // 重命名之后需要将重命名之后的文件重新保存,这样才能够在新路径下面找到这个文件
        document.getFile().renameTo(new File(PathKit.getWebRootPath()+"\\src\\file\\"+newName));
        //这个存储路径时需要与前面你在config的配置里面相对应的
        String savedPath ="\\src\\file";
        System.out.println("保存地址"+savedPath);
        // 构建document实体并赋值
        Document document1 = new Document();
        document1.setOriginalName(fileName);
        document1.setNewName(newName);
        document1.setSavedPath(savedPath);
        document1.setSuffix(suffix);
        HashMap<String,Object> data = new HashMap<>();
        if(!document1.save()){
            renderJson(BaseResult.fail("文件上传失败"));
            return;
        }
        data.put("fileId",document1.getId());
        data.put("filePath", PathKit.getWebRootPath()+savedPath+newName);
        renderJson(DataResult.data(data));

    }

    @Clear(AuthInterceptor.class)
    public void index() {
        renderText(PathKit.getWebRootPath());
    }

    /**
     * 文件下载操作，直接用绝对路径传给前端
     */
    public void downLoad() {
        renderFile(new File(PathKit.getWebRootPath() + "/file/upload"));
    }


    /**
     * 获取当前登陆者的姓名
     */
    public void getUnameByUId() {
        int uId = getAttr(BaseConstants.ACCOUNT_ID);
        Kv cond = Kv.by("uId", uId);
        User user = service.get(cond, "getByUId");
        String uName = user.getUName();
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("uName：", uName);
        renderJson(jsonObject);
    }

    /**
     * 获取管理员人数
     */
    public void getAdminNum() {
        User user = service.get("getAdminNum");
        renderJson(DataResult.data(user));
    }

    /**
     * 获取团队人员人数
     */
    public void getTeamMemberNum() {
        User user = service.get("getTeamMemberNum");
        renderJson(DataResult.data(user));
    }

    /**
     * 获取除自己以外其他团队成员
     */
    public void getAllUsersNameExceptMe() {
        int uId = getAttr(BaseConstants.ACCOUNT_ID);
        Kv cond = Kv.by("uId", uId);
        List<User> userList = service.list(cond,"getAllUsersNameExceptMe");
        renderJson(DataResult.data(userList));
    }

    /**
     * 获取所有管理员相关信息
     */
    @Param(name = "page", required = true)
    @Param(name = "pageSize", required = true)
    public void getAllAdmins(int page, int pageSize) {
        Page<Record> admins = Db.paginate(page, pageSize, "SELECT u_id,u_name,u_phone,u_sex,u_email,u_group,u_grade,u_ins,u_major,u_identity", "from user where u_identity = 1 and u_deleted = 0");
        renderJson(DataResult.data(admins));
    }

    /**
     * 获取所有团队成员相关信息
     */
    @Param(name = "page", required = true)
    @Param(name = "pageSize", required = true)
    public void getAllTeamMembers(int page, int pageSize) {
        Page<Record> TeamMembers = Db.paginate(page, pageSize, "select u_id,u_name,u_phone,u_sex,u_email,u_group,u_grade,u_ins,u_major,u_identity", "from user where u_identity = 0 and u_deleted = 0");
        renderJson(DataResult.data(TeamMembers));
    }

    /**
     * 获取所有未分组团队成员相关信息
     */
    @Param(name = "page", required = true)
    @Param(name = "pageSize", required = true)
    public void getAllTeamMemberOfNoGroup(int page, int pageSize) {
        Page<Record> TeamMembersOfNoGroup = Db.paginate(page, pageSize, "select u_id,u_name,u_phone,u_sex,u_email,u_group,u_grade,u_ins,u_major,u_identity", "from user where u_identity = 0 and u_deleted = 0 and u_group=0");
        renderJson(DataResult.data(TeamMembersOfNoGroup));
    }

    /**
     * 获取所有前端团队成员相关信息
     */
    @Param(name = "page", required = true)
    @Param(name = "pageSize", required = true)
    public void getAllTeamMemberOfFront(int page, int pageSize) {
        Page<Record> TeamMembersOfFront = Db.paginate(page, pageSize, "select u_id,u_name,u_phone,u_sex,u_email,u_group,u_grade,u_ins,u_major,u_identity", "from user where u_identity = 0 and u_deleted = 0 and u_group=1");
        renderJson(DataResult.data(TeamMembersOfFront));
    }

    /**
     * 获取所有后端团队成员相关信息
     */
    @Param(name = "page", required = true)
    @Param(name = "pageSize", required = true)
    public void getAllTeamMemberOfBack(int page, int pageSize) {
        Page<Record> getAllTeamMemberOfBack = Db.paginate(page, pageSize, "select u_id,u_name,u_phone,u_sex,u_email,u_group,u_grade,u_ins,u_major,u_identity", "from user where u_identity = 0 and u_deleted = 0 and u_group=2");
        renderJson(DataResult.data(getAllTeamMemberOfBack));
    }

    /**
     * 获取未分组团队成员相关信息
     * @param uGrade 年级信息 1-大一，2-大二，3-大三，4-大四，5-研究生及以上
     */
    @Param(name = "uGrade", required = true)
    @Param(name = "page", required = true)
    @Param(name = "pageSize", required = true)
    public void getTeamMemberOfNoGroup(int uGrade,int page, int pageSize) {
        Page<Record> noGroups = Db.paginate(page, pageSize, "SELECT u_id,u_name,u_phone,u_sex,u_email,u_group,u_grade,u_ins,u_major,u_identity", "from user where u_identity = 0 and u_group=0 and u_grade = ? and u_deleted = 0",uGrade);
        renderJson(DataResult.data(noGroups));
    }

    /**
     * 获取前端团队成员相关信息
     * @param uGrade 年级信息 1-大一，2-大二，3-大三，4-大四，5-研究生及以上
     */
    @Param(name = "uGrade", required = true)
    @Param(name = "page", required = true)
    @Param(name = "pageSize", required = true)
    public void getTeamMemberOfFront(int uGrade,int page, int pageSize) {
        Page<Record> front = Db.paginate(page, pageSize, "SELECT u_id,u_name,u_phone,u_sex,u_email,u_group,u_grade,u_ins,u_major,u_identity", "from user where u_identity = 0 and u_group=1 and u_grade = ? and u_deleted = 0",uGrade);
        renderJson(DataResult.data(front));
    }

    /**
     * 获取后端团队成员相关信息
     * @param uGrade 年级信息 1-大一，2-大二，3-大三，4-大四，5-研究生及以上
     */
    @Param(name = "uGrade", required = true)
    @Param(name = "page", required = true)
    @Param(name = "pageSize", required = true)
    public void getTeamMemberOfBack(int uGrade,int page, int pageSize) {
        Page<Record> back = Db.paginate(page, pageSize, "SELECT u_id,u_name,u_phone,u_sex,u_email,u_group,u_grade,u_ins,u_major,u_identity", "from user where u_identity = 0 and u_group=2 and u_grade = ? and u_deleted = 0",uGrade);
        renderJson(DataResult.data(back));
    }


}
